package cn.max.plat.db;

import com.mongodb.BasicDBObject;
import com.mongodb.BulkWriteOperation;
import com.mongodb.BulkWriteRequestBuilder;
import com.mongodb.BulkWriteResult;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

import java.util.Map;

/**
 * Created by Max-Goday on 15/7/24.
 */
public class DBUtils {

	public static DBObject getRepo(String repo_name) {

		BasicDBObject rpquery = new BasicDBObject("name", repo_name);

		return DBManager.getRepositoryRepo().findOne(rpquery);

	}

	public static DBCursor getClusterServersByRepo(String repo_name) {

		BasicDBObject cluster_query = new BasicDBObject("repo_name", repo_name);

		return DBManager.getClusterRepo().find(cluster_query);

	}

	public static DBObject getRepoClusterServerByIP(String repo_name, String server_ip) {

		BasicDBObject server_query = new BasicDBObject("repo_name", repo_name).append("ip", server_ip);

		return DBManager.getClusterRepo().findOne(server_query);

	}

	public static void update(DBCollection coll, BasicDBObject query, Map<String, Object> updateValues) {

		BulkWriteOperation builder = coll.initializeOrderedBulkOperation();

		BasicDBObject update;

		if (updateValues != null) {

			BulkWriteRequestBuilder _request_builder = builder.find(query);

			for (String key : updateValues.keySet()) {

				update =  new BasicDBObject("$set", new BasicDBObject(key, updateValues.get(key)));

				_request_builder.update(update);

			}

		}

		builder.execute();

	}

	//insert update remove demo
	public static void demos(DBCollection coll) {
		// 1. Ordered bulk operation
		BulkWriteOperation builder = coll.initializeOrderedBulkOperation();
		builder.insert(new BasicDBObject("_id", 1));
		builder.insert(new BasicDBObject("_id", 2));
		builder.insert(new BasicDBObject("_id", 3));

		builder.find(new BasicDBObject("_id", 1)).updateOne(new BasicDBObject("$set", new BasicDBObject("x", 2)));
		builder.find(new BasicDBObject("_id", 2)).removeOne();
		builder.find(new BasicDBObject("_id", 3)).replaceOne(new BasicDBObject("_id", 3).append("x", 4));

		BulkWriteResult result = builder.execute();

		// 2. Unordered bulk operation - no guarantee of order of operation
		builder = coll.initializeUnorderedBulkOperation();
		builder.find(new BasicDBObject("_id", 1)).removeOne();
		builder.find(new BasicDBObject("_id", 2)).removeOne();

		result = builder.execute();
	}

	public static void main(String[] args) {

		BasicDBObject query = new BasicDBObject("ip", "10.211.55.12");

		BulkWriteOperation builder = DBManager.getClusterRepo().initializeOrderedBulkOperation();


		BasicDBObject updates = new BasicDBObject("$set", new BasicDBObject("last_deployment_revision", "11re"));

		builder.find(query).update(updates);

		builder.execute();

		DBObject o = DBManager.getClusterRepo().findOne(query);


		System.out.println(o.get("last_deployment_revision"));
		System.out.println(o.get("last_deployment_at"));
		System.out.println(o.get("ip"));

	}

}
